﻿namespace Whut.ObjectSharePointMapper
{
    using System;
    using Microsoft.SharePoint;
    using Whut.ObjectSharePointMapper.Internals;

    public static class SessionHelper
    {
        /// <summary>
        /// Attach entity to given session.
        /// I hope you know what are you doing.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="item"></param>
        /// <param name="session"></param>
        /// <returns></returns>
        public static TEntity WrapAndAttach<TEntity>(SPListItem item, ISession session)
        {
            Session s = (Session)session;
            TEntity entity = s.entityHydrater.Hydrate<TEntity>(item);
            return entity;
        }

        /// <summary>
        /// Get item wraped by given entity in given session.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="session"></param>
        /// <returns></returns>
        public static SPListItem Unwrap<TEntity>(TEntity entity, ISession session)
        {
            Session s = (Session)session;
            ListInfo listInfo = s.metaDataStore.GetListInfoFor<TEntity>();
            int id = (int)listInfo.Id.PropertyInfo.GetValue(entity, null);
            return s.sessionLevelCache.TryFindSPListItem<TEntity>(id);
        }
    }
}
